package com.guo.mallproduct.exception;


import com.common.exception.BizCode;
import com.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

@Slf4j
@RestControllerAdvice(basePackages = "com.guo.mallproduct.controller")
public class ExceptionControllerAdvice {



    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){

        log.error("数据格式校验异常,{},异常类型,{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String, String> errorsMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorsMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCode.VALID_EXCRPTION.getCode(), BizCode.VALID_EXCRPTION.getMsg()).put("data",errorsMap);
    }


    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误原因：",throwable);
        return R.error(BizCode.UNKNOW_EXCEPTION.getCode(), BizCode.UNKNOW_EXCEPTION.getMsg());
    }

}
